/*
 * Copyright (c) 2025 zhangxiang (fishlikewater@126.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.github.fishlikewater.raiden.http.core.client;

import io.github.fishlikewater.raiden.core.ObjectUtils;
import io.github.fishlikewater.raiden.http.core.RequestWrap;
import io.github.fishlikewater.raiden.http.core.Response;
import io.github.fishlikewater.raiden.http.core.interceptor.RealInterceptorChain;
import io.github.fishlikewater.raiden.http.core.proxy.InterfaceProxy;
import lombok.SneakyThrows;

import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;

/**
 * {@code StandaloneHttpRequestClient}
 * 独立的http请求客户端
 *
 * @author zhangxiang
 * @since 2025/7/10
 */
public class StandaloneHttpRequestClient implements InterfaceProxy {

    /**
     * 同步执行
     *
     * @param requestWrap 请求参数
     * @param <T>         泛型
     * @return 结果
     */
    @SneakyThrows(Throwable.class)
    public <T> HttpResponse<T> executeSync(RequestWrap requestWrap) {
        requestWrap.setSync(true);
        Response<T> response = getTResponse(requestWrap);
        return response.getSyncResponse();
    }

    /**
     * 异步执行
     *
     * @param requestWrap 请求参数
     * @param <T>         泛型
     * @return 响应结果
     */
    @SneakyThrows(Throwable.class)
    public <T> CompletableFuture<HttpResponse<T>> executeAsync(RequestWrap requestWrap) {
        requestWrap.setSync(false);
        Response<T> response = getTResponse(requestWrap);
        return response.getAsyncResponse();
    }

    @Override
    public <T> T getInstance(Class<T> interfaceClass) {
        throw new UnsupportedOperationException();
    }

    // ----------------------------------------------------------------

    private <T> Response<T> getTResponse(RequestWrap requestWrap) throws IOException, InterruptedException {
        if (ObjectUtils.isNullOrEmpty(requestWrap.getInterceptors())) {
            requestWrap.setInterceptors(new ArrayList<>());
        }
        this.handleInterceptor(requestWrap);
        RealInterceptorChain chain = new RealInterceptorChain(requestWrap);
        return chain.proceed();
    }
}
